import React, { Suspense } from 'react';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';

const Home = React.lazy(() => import('@/pages/Home' /* webpackChunkName: "Home" */));
const HomeDemo = React.lazy(() => import('@/pages/Home/Demo' /* webpackChunkName: "HomeDemo" */));
const LoginPage = React.lazy(() => import('@/pages/Login' /* webpackChunkName: "LoginPage" */));

export const routers: any[] = [
  {
    path: '/',
    redirectPath: '/home',
  },
  {
    path: '/home',
    element: Home,
    children: [
      {
        path: '/home',
        redirectPath: '/home/demo',
      },
      {
        path: '/home/demo',
        element: HomeDemo,
      },
    ],
  },
  {
    path: '/login',
    element: LoginPage,
  },
  // {
  //   path: '*',
  //   element: <NotFoundPage />,
  // },
];

const Root = () => {
  function generateRoutes(routes: any[]): JSX.Element[] {
    function traverse(route: any) {
      const { element: Component, path, redirectPath } = route;
      let element: any = null;
      if (redirectPath) {
        element = (
          <Route key={path} path={path} element={<Navigate to={redirectPath} replace />}></Route>
        );
      } else {
        element = (
          <Route key={path} path={path} element={<Component />}>
            {route.children && route.children?.map((child: any) => traverse(child))}
          </Route>
        );
      }

      return element;
    }
    return routes.map((route) => traverse(route));
  }
  return (
    <BrowserRouter>
      <Suspense fallback={<div>加载中...</div>}>
        <TransitionGroup>
          <CSSTransition timeout={3000} classNames="route">
            <Routes>{generateRoutes(routers)}</Routes>
          </CSSTransition>
        </TransitionGroup>
      </Suspense>
    </BrowserRouter>
  );
};
export default Root;
